<template>
  <div class="create-comment">
    <div class="comment-form">
      <h3>发表评价</h3>

      <div class="form-group">
        <div class="rating-stars">
          <svg
            v-for="star in 5"
            :key="star"
            xmlns="http://www.w3.org/2000/svg"
            width="24"
            height="24"
            viewBox="0 0 24 24"
            :fill="star <= form.rating ? '#ffc107' : 'none'"
            :stroke="star <= form.rating ? '#ffc107' : '#ddd'"
            stroke-width="2"
            @click="form.rating = star"
          >
            <path
              d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"
            />
          </svg>
        </div>
      </div>

      <div class="form-group">
        <label for="content">评论内容</label>
        <textarea
          id="content"
          v-model="form.content"
          placeholder="请输入您的评价..."
          rows="4"
          maxlength="500"
        ></textarea>
        <span class="char-count">{{ form.content.length }}/500</span>
      </div>

      <div class="form-group">
        <label>上传图片（最多5张）</label>
        <div class="image-upload">
          <div
            v-for="(preview, index) in imagePreviews"
            :key="index"
            class="image-preview"
            @click="removeImage(index)"
          >
            <img :src="preview" alt="预览图片" />
            <div class="remove-btn">×</div>
          </div>

          <label v-if="imagePreviews.length < 5" for="image-upload" class="upload-btn">
            <i class="fa fa-plus"></i>
            <span>添加图片</span>
          </label>

          <input
            id="image-upload"
            type="file"
            multiple
            accept="image/*"
            @change="handleImageUpload"
            style="display: none"
          />
        </div>
      </div>

      <button :disabled="!canSubmit || submitting" @click="submitComment" class="submit-btn">
        <span v-if="submitting">提交中...</span>
        <span v-else>发表评价</span>
      </button>

      <div v-if="submitError" class="error-message">
        {{ submitError }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { commentsApi, type CreateCommentParams } from '@/api/comments'
import { ElMessage } from 'element-plus'

interface Props {
  goodsId: number
  orderId: number
}

interface Emits {
  (event: 'success'): void
  (event: 'cancel'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const form = ref({
  rating: 0, // 默认0分，用户必须选择
  content: '',
})

const imageFiles = ref<File[]>([])
const imagePreviews = ref<string[]>([])
const submitting = ref(false)
const submitError = ref('')

const canSubmit = computed(() => {
  return form.value.rating > 0 && form.value.rating <= 5 && form.value.content.trim().length > 0
})

const handleImageUpload = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (!input.files?.length) return

  const files = Array.from(input.files)
  const remainingSlots = 5 - imageFiles.value.length

  if (files.length > remainingSlots) {
    ElMessage.warning(`最多只能上传5张图片，还可以上传${remainingSlots}张`)
    files.splice(remainingSlots)
  }

  files.forEach((file) => {
    if (!file.type.startsWith('image/')) {
      ElMessage.warning('请选择图片文件')
      return
    }

    // 生成预览
    const reader = new FileReader()
    reader.onload = (e) => {
      imagePreviews.value.push(e.target?.result as string)
    }
    reader.readAsDataURL(file)

    imageFiles.value.push(file)
  })

  // 清空input以便再次选择相同的文件
  input.value = ''
}

const removeImage = (index: number) => {
  imagePreviews.value.splice(index, 1)
  imageFiles.value.splice(index, 1)
}

const submitComment = async () => {
  if (!canSubmit.value) return

  submitting.value = true
  submitError.value = ''

  try {
    const params: CreateCommentParams = {
      goods: props.goodsId,
      order: props.orderId,
      content: form.value.content.trim(),
      rating: form.value.rating,
      images: imageFiles.value,
    }

    await commentsApi.createComment(params)

    ElMessage.success('评价发表成功！')
    emit('success')

    // 重置表单
    form.value = { rating: 5, content: '' }
    imageFiles.value = []
    imagePreviews.value = []
  } catch (error: any) {
    console.error('发表评价失败:', error)
    submitError.value = error.response?.data?.error || '发表评价失败，请重试'
    ElMessage.error(submitError.value)
  } finally {
    submitting.value = false
  }
}

// 监听商品ID变化重置表单
watch(
  () => props.goodsId,
  () => {
    form.value = { rating: 0, content: '' } // 重置为0分
    imageFiles.value = []
    imagePreviews.value = []
  },
)
</script>

<style scoped lang="scss">
.create-comment {
  .comment-form {
    background: white;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

    h3 {
      margin: 0 0 24px 0;
      font-size: 18px;
      color: #333;
      border-bottom: 1px solid #eee;
      padding-bottom: 12px;
    }

    .form-group {
      margin-bottom: 20px;

      label {
        display: block;
        margin-bottom: 8px;
        font-weight: 600;
        color: #333;
      }

      .rating-stars {
        display: flex;
        gap: 8px;
        cursor: pointer;

        svg {
          transition: all 0.2s;

          &:hover {
            transform: scale(1.2);
          }
        }
      }

      textarea {
        width: 100%;
        padding: 12px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        resize: vertical;
        font-family: inherit;
        font-size: 14px;

        &:focus {
          outline: none;
          border-color: #409eff;
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }
      }

      .char-count {
        display: block;
        text-align: right;
        font-size: 12px;
        color: #999;
        margin-top: 4px;
      }

      .image-upload {
        display: flex;
        gap: 12px;
        flex-wrap: wrap;

        .image-preview {
          position: relative;
          width: 80px;
          height: 80px;
          border-radius: 4px;
          overflow: hidden;
          cursor: pointer;
          transition: transform 0.2s;

          &:hover {
            transform: scale(1.05);

            .remove-btn {
              opacity: 1;
            }
          }

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .remove-btn {
            position: absolute;
            top: 4px;
            right: 4px;
            width: 20px;
            height: 20px;
            background: rgba(0, 0, 0, 0.7);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            opacity: 0;
            transition: opacity 0.2s;
          }
        }

        .upload-btn {
          width: 80px;
          height: 80px;
          border: 2px dashed #dcdfe6;
          border-radius: 4px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition: border-color 0.2s;

          &:hover {
            border-color: #409eff;
            color: #409eff;
          }

          i {
            font-size: 20px;
            margin-bottom: 4px;
          }

          span {
            font-size: 12px;
            color: #666;
          }
        }
      }
    }

    .submit-btn {
      width: 100%;
      padding: 12px;
      background-color: #409eff;
      color: white;
      border: none;
      border-radius: 4px;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      transition: background-color 0.2s;

      &:hover:not(:disabled) {
        background-color: #66b1ff;
      }

      &:disabled {
        background-color: #c0c4cc;
        cursor: not-allowed;
      }
    }

    .error-message {
      margin-top: 12px;
      padding: 8px 12px;
      background-color: #fef0f0;
      color: #f56c6c;
      border-radius: 4px;
      font-size: 14px;
    }
  }
}

@media (max-width: 768px) {
  .create-comment {
    .comment-form {
      padding: 16px;

      .form-group {
        .image-upload {
          .image-preview,
          .upload-btn {
            width: 60px;
            height: 60px;
          }
        }
      }
    }
  }
}
</style>
